package com.sxran.im.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class JWTService {
    private final static byte [] KEY = "1234".getBytes();
    public static final String USER_ID = "userId";

    /**
     * 生成jwt的内容
     * @param userId
     * @return
     */
    public String createToken(String userId ){
        Map<String, Object> payload = new HashMap<>();
        payload.put(USER_ID,userId);
        return createToken(payload);
    }

    /**
     * 生成jwt的内容
     * @param payload
     * @return
     */
    public String createToken(Map<String, Object> payload){
        return JWTUtil.createToken( payload,KEY);
    }

    /**
     * 校验
     * @param jwt
     * @return
     */
    public boolean verify(String jwt){
        return JWTUtil.verify(jwt,KEY);
    }

    /**
     * 获得map里面 key对应的内容。
     * @param jwt
     * @param key
     * @return
     */
    public Object parseToken(String jwt,String key){
        JWT parsedToken = JWTUtil.parseToken(jwt);
        return parsedToken.getPayload(key);
    }

    public String getUserId(String jwt){
        return StrUtil.toStringOrNull(parseToken(jwt,USER_ID));
    }


    public static void main(String[] args) {
        JWTService jwtService = new JWTService();
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("uid", Integer.parseInt("123"));
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
            }
        };
        String token = jwtService.createToken(map);

        JWT parsedToken = JWTUtil.parseToken(token);
        System.out.println(parsedToken.getPayload("sub"));
        System.out.println(parsedToken.getPayload("expire_time"));
        System.out.println(parsedToken.getPayload());
    }
}
